package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"gooded/goodedrpc/goodedrpc"
	"gooded/goodedrpc/internal/svc"
	"gooded/model/mysql"
	"gooded/model/redisinit"
	"gooded/pkg"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *goodedrpc.RegisterRequest) (*goodedrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	code := in.Score
	get := redisinit.Client.Get("Caption" + in.Username)
	if get.Val() != code {
		return nil, fmt.Errorf("图形验证失败")
	}

	codes := in.SendSms
	gets := redisinit.Client.Get("SendSms" + in.Username + "login")
	if gets.Val() != codes {
		return nil, fmt.Errorf("短信验证失败")
	}

	var users mysql.Good
	mysql.DB.Where("username = ?", in.Username).Find(&users)

	if users.Username != "" {
		return nil, fmt.Errorf("用户已注册,请重新输入")
	}

	good := mysql.Good{
		Username: in.Username,
		Password: pkg.MD5(in.Password),
	}
	mysql.DB.Create(&users)
	
	return &goodedrpc.RegisterResponse{
		Id: int64(good.ID),
	}, nil
}
